package com.bw.module_mine.login.ui

import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.text.Spannable
import android.text.SpannableString
import android.text.style.RelativeSizeSpan
import android.util.Log
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bw.lib_common.base.BaseFragment
import com.bw.lib_common.base.state.Default
import com.bw.lib_common.base.state.Empty
import com.bw.lib_common.base.state.Failed
import com.bw.lib_common.base.state.Loading
import com.bw.lib_common.base.state.Success
import com.bw.lib_common.observeWithLifecycle
import com.bw.module_mine.R
import com.bw.module_mine.databinding.FragmentRegisterBinding
import com.bw.module_mine.login.viewmodel.UserViewModel
import com.bw.module_mine.utils.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import java.util.Random
import java.util.Timer
import java.util.TimerTask

@Suppress("UNREACHABLE_CODE")
@AndroidEntryPoint
class RegisterFragment : BaseFragment<UserViewModel,FragmentRegisterBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_register

    private val mViewModel:UserViewModel by activityViewModels()
    private lateinit var mNavController: NavController

    private lateinit var timer: Timer
    private var isTimerRunning = false  // 新增状态标记，避免重复触发


    override fun initView() {
        super.initView()
        mViewModel.setShowingFragmentTag(LoginFragment::class.simpleName!!)
        mNavController = Navigation.findNavController(mBinding.root)

    }

    override fun initData() {
        mBinding.viewmodel = mViewModel

        mBinding.btnCode.setOnClickListener {

            val phone = mViewModel.registerPhone.value
            val password = mViewModel.registerPassword.value

            if(phone.length == 0){
                ToastUtils.showLong(context, "请先输入电话号")
                return@setOnClickListener
                Log.d("clb",phone)
            }


            if (isTimerRunning) return@setOnClickListener

            val code = Random().nextInt(900000) + 100000
            ToastUtils.showLong(context, "验证码已发送：$code")

            object : CountDownTimer(60_000, 1000) {  // 总时长10秒，间隔1秒

                override fun onTick(millisUntilFinished: Long) {
                    val seconds = millisUntilFinished / 1000
                    mBinding.btnCode.text = "$seconds 秒后重新获取验证码"
                    // 创建可变文本，设置倒计时部分为较小字体
                    val spannable = SpannableString("$seconds 秒后重新获取验证码")
                    spannable.setSpan(
                        RelativeSizeSpan(0.6f),  // 0.8f 表示原字体的80%大小
                        0,  // 开始位置
                        12,  // 结束位置（秒数字符串长度）
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    mBinding.btnCode.text = spannable
                    mBinding.btnCode.isEnabled = false
                }

                override fun onFinish() {
                    mBinding.btnCode.text = "重新获取验证码"
                    mBinding.btnCode.isEnabled = true
                    isTimerRunning = false
                }

            }.start()
            isTimerRunning = true
        }


        mBinding.btnRegister.setOnClickListener{
            register()
        }
    }

    override fun initListener() {
        mViewModel.RegisterEvent.observeWithLifecycle(this){
            when(it){
                is Success -> {
                    ToastUtils.showLong(context, "注册成功")
                    mNavController.navigate(R.id.action_registerFragment_to_loginFragment)
                }
                is Failed -> {
                    ToastUtils.showLong(context, it.message)
                }
                is Loading -> {
                    ToastUtils.showLong(context, "正在注册中...")
                }

                Default -> {

                }
                Empty -> {

                }
            }
        }

    }

    fun register() {
        val phone = mViewModel.registerPhone.value
        val password = mViewModel.registerPassword.value
        val passwordAgain = mViewModel.registerPasswordAgain.value
        if(phone.length == 0){
            ToastUtils.showLong(context, "请先输入电话号")
            return
        }

        if(password.length == 0){
            ToastUtils.showLong(context, "请先输入密码")
            return
        }

        if(password != passwordAgain){
            ToastUtils.showLong(context, "两次密码不一致")
            return
        }

        mViewModel.register(password,phone)

    }

    override fun onDestroy() {
        super.onDestroy()
        if (::timer.isInitialized) {
            timer.cancel()
        }
    }


}